package DataStructure.demo01;

public class HashBuck {
    static class Node {
        public int key;
        public int value;
        public Node next;

        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }
    public Node[] array;
    public int usedSize;// 记录使用大小
    public static final float LOAD_FACTOR = 0.75f;

    public HashBuck(){
        array = new Node[10];
    }

    public void put(int key, int value){
        int index = key % array.length;
        //遍历index下的链表，看是否存在key，存在更新value，不存在使用尾插法插入
        Node cur = array[index];
        Node pre = null;
        while (cur != null){
            if(cur.key == key){
                //更新value
                cur.value = value;
                return;
            }
            pre = cur;
            cur = cur.next;
        }
        Node node = new Node(key, value);
        if(pre == null){
            array[index] = node;
        }else{
            pre.next = node;
        }
        usedSize++;
        if (getLoadFactor() > LOAD_FACTOR){
            //扩容！！！
            resize();
        }
    }

    //采用尾插法扩容！！！
    private void resize(){
        Node[] newArray = new Node[array.length*2];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null) {
                int newIndex = cur.key % newArray.length;
                Node next = cur.next;
                Node tmp = newArray[newIndex];
                Node pre = null;
                while (tmp != null){
                    pre = tmp;
                    tmp = tmp.next;
                }
                if(pre == null){
                    newArray[newIndex] = cur;
                }else{
                    pre.next = cur;
                }
                cur.next = null;
                cur = next;
            }
        }
        array = newArray;
    }

    private float getLoadFactor(){
        return usedSize*1.0f / array.length;
    }

    public int get(int key){
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null){
            if(cur.key == key){
                return cur.value;
            }
            cur = cur.next;
        }
        return -1;
    }
}
